package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"supplier/basic/config"
	"supplier/basic/model"
	"supplier/handler/request"
)

func List(c *gin.Context) {
	var SupplierList request.SupplierList
	err := c.ShouldBind(&SupplierList)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var Supplier []model.Suppliers
	page := SupplierList.Page
	if page <= 0 {
		page = 1
	}

	pageSize := SupplierList.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	err = config.DB.Offset(offset).Limit(pageSize).Find(&Supplier).Error
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": Supplier,
	})
}

func State(c *gin.Context) {
	var States request.StateReq
	err := c.ShouldBind(&States)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var Product model.Products
	err = config.DB.Where("id=?", States.SupplerId).Find(&Product).Limit(1).Error
	if err != nil {
		return
	}
	if Product.ProductState == 1 {
		config.DB.Model(&Product).Where("id=?", States.SupplerId).Update("product_state", 2)

	} else {
		config.DB.Model(&Product).Where("id=?", States.SupplerId).Update("product_state", 1)

	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": nil,
	})
}

func Add(c *gin.Context) {
	var States request.AddReq
	err := c.ShouldBind(&States)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	supp := model.Suppliers{
		SupplierName:     States.SupplierName,
		SupplierContacts: States.SupplierContacts,
		SupplierArea:     States.SupplierArea,
		SupplierFounder:  States.SupplierFounder,
	}

	config.DB.Create(&supp)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": supp,
	})
}
